<template>
<div class="checkout flex-box-div">
    <div class="plr address-box height-70 bgc-white flex-center" @click="$router.push('/address?redirect=checkout')">
        <img src="@/assets/image/location.png" alt="" class="height-34 width-34">
        
        <template v-if="!$store.getters['user/address'].id">
            <div class="flex-1">
                请选择地址
            </div>
        </template>
        <template v-else>
            <div class="flex-1 text-left pl10 pr10" >
                <div>
                    <span class="blod">{{$store.getters['user/address'].name}}</span> <span class="ml6">{{$store.getters['user/address'].phone}}</span>
                </div>
                <div class="mt4">
                    {{$store.getters['user/address'].addr}}{{address_info.addr_extra}}
                </div>
            </div>
            <van-icon name="arrow" color="#8B8B8B" size="16" />
        </template>
    </div>

    <div class="plr mt12 height-50 bgc-white flex-center" @click="$router.push('/invoice?redirect=checkout')">
        <template v-if="!$store.getters['user/default_invoice'].id">
            <div class="flex-1">
                请选择发票
            </div>
        </template>
        <div class="blod">发票：</div>
        <div class="flex-1 text-right pr10">{{ $store.getters['user/default_invoice'].ltd_name }}</div>
        <van-icon name="arrow" size="14" />
    </div>
	
    <div class="mt12">
        <div class="item plr pt10 pb10 mb10" v-for="(item, index) in goods_list" :key="index">
            <div class="shop-box-data flex-1 flex-center height100" >
                <img :src="item.cover_img" alt="">
                <div class="msg flex-1 text-left height-80">
                    <div class=" blod name van-multi-ellipsis--l2 fz-12">
                        {{item.name}}
                    </div>
                    <div class="fz-16 blod">
                        <span class="price">￥{{item.price}}</span> <i class="fz-12 ml10">x{{item.buy_num}}</i>
                    </div>
                    <div class="text-gray fz-12 flex-center-space-between">
                        <div class="padd">
                            <!-- 库存数量：200套 -->
                            <div class="flex-1"><van-icon name="location-o" />{{item.city}}</div>
                        </div>
                    </div>
                </div>
            </div>
			
			
        </div>
		
		
    </div>

    <van-submit-bar
        :loading="loading"
        :price="total_price"
        button-text="提交订单"
        @submit="onSubmit"
        >
        <div @click="showList = true">优惠券 <span class="price fz-12" v-if="chosenCoupon >= 0"> -{{ coupons[chosenCoupon].valueDesc }} </span> </div>
    </van-submit-bar>

    <!-- 优惠券列表 -->
    <van-popup
            v-model="showList"
            round
            position="bottom"
            style="height: 90%; padding-top: 4px;"
        >
        <van-coupon-list
            :show-exchange-bar="false"
            :coupons="coupons"
            :disabled-coupons="disabledCoupons"
            :chosen-coupon="chosenCoupon"
            @change="onChange"
        />
    </van-popup>
</div>
</template>

<script>
export default {
    data () {
        return {
            loading: false,
			// total_price:0,
			goods_list:[],
			channel:'',
			goods_id:0,
			address_list:[],
			address_info:'',
			invoice_list:[],
			invoice_info:'',

            showList: false,
            coupons: [
                // {
                //     available: 1,
                //     condition: '无使用门槛\n最多优惠12元', // 满减条件
                //     reason: '', // 不可用原因，优惠券不可用时展示
                //     value: 150, // 折扣券优惠金额，单位分
                //     name: '优惠券名称',
                //     startAt: 1489104000,
                //     endAt: 1514592000,
                //     valueDesc: '1.5',
                //     unitDesc: '元',
                // }
            ], // 可用 券 列表
            disabledCoupons: [], // 不可用 券 列表
            chosenCoupon: -1 // 选中的优惠券的索引
        }
    },
    computed: {
        total_price () {
            let coupon_price = this.chosenCoupon >= 0 ? this.coupons[this.chosenCoupon].valueDesc : 0
            return (this.goods_list.reduce((p, c) => {
                return (p += (+c.price * c.buy_num))
            }, 0) - coupon_price) * 100 // 总价 千分位
        }
    },
	created: function() {
		
		this.getBaseInfo()
	},
    methods: {
        // 获取优惠券列表
        getCouponList () {
            this.$goods.getPreview().then(res => {
                // console.log(res)
                const { data } = res
                if (data) {
                    var list = []
                    var disabledCoupons = []
                    // var nolist = []
                    let tot_price = this.total_price / 100
                    data.coupon_list.forEach(item => {
                        if (tot_price >= item.full_money) {
                            const dates = item.expire_date.split('~')
                            if (item.goods === null) {
                                list.push({
                                    id: item.id,
                                    condition: item.pay_money_intro, // 满减条件
                                    reason: '', // 不可用原因，优惠券不可用时展示
                                    value: item.money * 100, // 折扣券优惠金额，单位分
                                    name: item.name,
                                    startAt: +new Date(dates[0]),
                                    endAt: +new Date(dates[1]),
                                    valueDesc: item.money,
                                    unitDesc: '元',
                                })
                            } else {
                                let ids = this.goods_list.map(v => v.id)
                                if (ids.every(v => item.goods.indexOf(v) > -1)) {
                                    list.push({
                                        id: item.id,
                                        condition: item.pay_money_intro, // 满减条件
                                        reason: '', // 不可用原因，优惠券不可用时展示
                                        value: item.money * 100, // 折扣券优惠金额，单位分
                                        name: item.name,
                                        startAt: +new Date(dates[0]),
                                        endAt: +new Date(dates[1]),
                                        valueDesc: item.money,
                                        unitDesc: '元',
                                    })
                                } else {
                                    disabledCoupons.push({
                                        id: item.id,
                                        condition: item.pay_money_intro, // 满减条件
                                        reason: '指定商品优惠券', // 不可用原因，优惠券不可用时展示
                                        value: item.money * 100, // 折扣券优惠金额，单位分
                                        name: item.name,
                                        startAt: +new Date(dates[0]),
                                        endAt: +new Date(dates[1]),
                                        valueDesc: item.money,
                                        unitDesc: '元',
                                    })
                                }
                            }
                        } else {
                            const dates = item.expire_date.split('~')
                            disabledCoupons.push({
                                id: item.id,
                                condition: item.pay_money_intro, // 满减条件
                                reason: item.pay_money_intro, // 不可用原因，优惠券不可用时展示
                                value: item.money * 100, // 折扣券优惠金额，单位分
                                name: item.name,
                                startAt: +new Date(dates[0]),
                                endAt: +new Date(dates[1]),
                                valueDesc: item.money,
                                unitDesc: '元',
                            })
                        }
                    })
                    // console.log(list)
                    this.coupons = list
                    this.disabledCoupons = disabledCoupons
                }
            })
        },
        onChange (val) {
            // console.log(val, val1)
            this.chosenCoupon = val
            this.showList = false
        },
        // 获取 下单 商品
		getBaseInfo (){
			const that = this
			that.channel = that.$route.query.channel
			if(that.channel === 'cart'){ // 购物车
				that.$goods.findCart().then((res) => {
					const data = res.data
					// console.log(data)
					// that.goods_list = data.filter(goods => goods.is_checked === 1) ||[]
                    let list = []
					data.mch_goods_list.forEach(item => {
                        // return item
                        item.goods_list.forEach((goods) => {
                            if (goods.is_checked === 1) {
                                let sku = {}
                                if (goods.sku_id !== 0) {
                                    var go = goods.sku_price.find(v => v.id === goods.sku_id)
                                    sku.price = go.price
                                    sku.stock = go.stock
                                }
                                list.push({ ...goods, ...sku })

                            }
                        })
                    })
                    // console.log(list)
                    that.goods_list = list
				})
			}else{ // 立即购买
				// that.goods_id=that.$route.query.goods_id
				// var param = {
				// 	id: that.goods_id
				// }
                // console.log(this.$route.query.goods_id)
				this.$goods.getGoodsDetail(this.$route.query.goods_id).then((res) => {
                    // console.log(res)
                    // if (data.detail.sku_price.length > 0) {
                    //     // that.suk_id = data.detail.sku_price[0].id
                    //     that.suk_id = 0
                    //     that.sku_price = data.detail.sku_price
                    // }
                    let data = {}
                    if (res.data.detail.sku_price.length > 0) {
                        data = {
                            price: res.data.detail.sku_price[this.$route.query.sku_id].price
                        }
                    } else {
                        data = {
                            price: res.data.detail.price
                        }
                    }
                    this.goods_list = [{...res.data.detail, buy_num: this.$route.query.count, sku_id: this.$route.query.sku_id, ...data}]
                })
				
			}
			
			
			// that.$user.getAddressList().then(function(res){
			// 	const data = res.data||{}
			// 	that.address_list = data.list||[]
			// 	that.address_info = data.list[0]||[]
			// })
			
			// that.$buyer.invoice().then(function(res){
			// 	const data = res.data||{}
			// 	that.invoice_list = data.list||[]
				
			// 	that.invoice_info = data.list[0]||[]
			// })
			setTimeout(() => {
                this.getCouponList()

            }, 1000)
			
			
		},
        onSubmit () {
			let data = {}
			// var data = {
			// 	channel: this.channel,
			// 	addr_id: this.$store.getters['user/address'].id,
			// 	invoice_id: this.$store.getters['user/default_invoice'].id,
			// }
            // let datas = { // 立即购买
            //     goods_id: this.goods_list[0].id,
            //     sku_id: '',
            //     num: '',
			// 	addr_id: this.$store.getters['user/address'].id,
			// 	invoice_id: this.$store.getters['user/default_invoice'].id
            // }
			if (this.$route.query.channel === 'cart') { // 购物车
                data = {
                    extra: this.chosenCoupon >= 0 ? [{ coupon_id: this.coupons[this.chosenCoupon].id }] : [],
                    channel: this.channel,
                    addr_id: this.$store.getters['user/address'].id,
                    invoice_id: this.$store.getters['user/default_invoice'].id,
                }
            } else {
                // 立即购买
                data = { // 立即购买
                    extra: this.chosenCoupon >= 0 ? [{ coupon_id: this.coupons[this.chosenCoupon].id }] : [],
                    channel: '',
                    goods_id: this.goods_list[0].id,
                    sku_id: this.goods_list[0].sku_price.length > 0 ? this.goods_list[0].sku_price[this.goods_list[0].sku_id].id : 0,
                    num: +this.goods_list[0].buy_num,
                    addr_id: this.$store.getters['user/address'].id,
                    invoice_id: this.$store.getters['user/default_invoice'].id
                }
            }
            // console.log(data)
			this.$goods.payOrder(data).then((res) => {
				const data = res.data||{}
				if (data.need_pay === 1){
					
					this.$router.push(`/pay?id=${data.order_id}`)
				}else{
					this.$router.push(`/logistic?id=${data.order_id}`)
				}
				
			})
            
        }
    }
}
</script>

<style lang="less" scoped>
.checkout {
    padding-bottom: 50px;
}

.item {
    background-color: #fff;
    &:last-child {
        margin-bottom: 20px;
    }
    .shop-box-data {
        img {
            height: 80px;
            min-width: 80px;
            width: 80px;
        }
        .msg {
            // height: 56px;
            padding-left: 10px;
            width: 100%;
            .name {
                width: 100%;
            }
        }
    }
    .tag- {
        border-radius: 4px;
        margin-right: 10px;
    }
}
</style>
